<template>
  <div class="all">
    <el-container class="all_content">
      <Sidebar/>
      <el-container class="all_main">
        <el-header class="head">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item class="item"><span class="t">APP学员列表</span></el-breadcrumb-item>
          </el-breadcrumb>
        </el-header>
        <el-main class="main">
          <div class="search-area">
            <div class="s">
              <el-input
                  v-model="searchForm.keyword"
                  placeholder="输入手机号、昵称或用户名搜索"
                  clearable
                  style="width: 1000px; height:40px;"
                  @keyup.enter="fetchStudents"
              >
                <template #append>
                  <el-button @click="fetchStudents">  搜索  </el-button>
                </template>
              </el-input>
            </div>

          </div>
            <div class="table-wrapper" style="width: 100%;">
              <el-table
                  :data="studentList"
                  border
                  style="width: 90%;font-family: 'monospace';"
                  :default-sort="{ prop: 'createTime', order: 'descending' }"
                  @sort-change="handleSortChange"
                  v-loading="loading"
                  element-loading-text="数据加载中..."
              >
                <el-table-column type="index" label="序号" min-width="50" />
                <el-table-column prop="name" label="姓名" min-width="100" />
                <el-table-column prop="phone" label="手机号" min-width="140" />
                <el-table-column label="创建时间" min-width="150">
                  <template #default="scope">
                    {{ formatCreateTime(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="学员类型" min-width="120">
                  <template #default="scope">
                    {{ scope.row.type === 'app' ? 'APP学员' : 'Web学员' }}
                  </template>
                </el-table-column>
                <el-table-column prop="vipStatus" label="VIP状态" min-width="120">
                  <template #default="scope">
                    {{ getVipStatusText(scope.row.vipStatus) }}
                  </template>
                </el-table-column>
                <el-table-column prop="supervisorInfo.name" label="上级教练" width="120" />

                <el-table-column label="操作" min-width="120">
                  <template #default="scope">
                    <el-button plain @click="open(scope.row)"
                               width="110"
                               style="display: inline-block;margin-bottom: 5px"
                    >&nbsp;查看详情&nbsp;</el-button>
                    <el-button plain @click="openit(scope.row)"
                               width="110"
                               style="display: inline-block; margin-bottom: 5px"
                    >&nbsp;转教练&nbsp;</el-button>
                  </template>
                </el-table-column>

              </el-table>
            </div>
            <!--分页器-->
          <div class="pagination" style="padding: 20px 0 0 90px;">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5,10, 20, 30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            />
          </div>
        </el-main>
      </el-container>
      </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import {getStudents} from "@/api/Students.js";
import {change} from '@/api/change.js';
import { useRouter } from 'vue-router';
const router = useRouter();
const studentList = ref([]);  //学生列表
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const loading = ref(false);
import Sidebar from '@/components/Sidebar.vue';
const formatCreateTime = (timeStr) => {
  if (!timeStr) return '';
  return timeStr.split('T')[0];

};


const open = (rowData) => {

  const fieldMap = {

    id: '编号',
    name: '姓名',
    phone: '手机号',
    createTime: '创建时间',
    type: '学员类型',
    vipStatus: 'VIP状态',


    'supervisorInfo.id': '上级教练ID',
    'supervisorInfo.name': '上级教练姓名',
    'supervisorInfo.phone': '上级教练电话',


    'vipInfo.id': 'VIP订单ID',
    'vipInfo.orderNo': '订单号',
    'vipInfo.orderTime': '下单时间',
    'vipInfo.activateTime': '激活时间',
    'vipInfo.vipExpireTime': 'VIP到期时间'
  };


  const formatTime = (timeStr) => {
    return timeStr ? timeStr.split('T')[0] : '未设置';
  };


  let detailContent = '<div class="detail-container">';


  for (const key in rowData) {
    if (key === 'supervisorInfo' || key === 'vipInfo') continue; // 单独处理嵌套对象

    const displayKey = fieldMap[key] || key;
    const displayValue = key === 'createTime'
        ? formatTime(rowData[key])
        : rowData[key] || '未设置';

    detailContent += `
      <div class="detail-row">
        <span class="detail-key"> ${displayKey}： </span>
        <span class="detail-value">${displayValue}</span>
      </div>
    `;
  }


  if (rowData.supervisorInfo && Object.keys(rowData.supervisorInfo).length > 0) {
    detailContent += '<div class="detail-group"><div class="detail-group-title">上级教练信息</div>';
    for (const subKey in rowData.supervisorInfo) {
      const fullKey = `supervisorInfo.${subKey}`;
      const displayKey = fieldMap[fullKey] || subKey;
      const displayValue = rowData.supervisorInfo[subKey] || '未设置';

      detailContent += `
        <div class="detail-row">
          <span class="detail-key">${displayKey}：</span>
          <span class="detail-value">${displayValue}</span>
        </div>
      `;
    }
    detailContent += '</div>';
  }

  if (rowData.vipInfo && Object.keys(rowData.vipInfo).length > 0) {
    detailContent += '<div class="detail-group"><div class="detail-group-title">VIP信息</div>';
    for (const subKey in rowData.vipInfo) {
      const fullKey = `vipInfo.${subKey}`;
      const displayKey = fieldMap[fullKey] || subKey;
      const displayValue = subKey.includes('Time')
          ? formatTime(rowData.vipInfo[subKey])
          : rowData.vipInfo[subKey] || '未设置';

      detailContent += `
        <div class="detail-row">
          <span class="detail-key">${displayKey}：</span>
          <span class="detail-value">${displayValue}</span>
        </div>
      `;
    }
    detailContent += '</div>';
  }

  detailContent += '</div>';

  // 打开弹窗
  ElMessageBox.alert(
      detailContent,
      '学员详情',
      {
        confirmButtonText: 'OK',
        dangerouslyUseHTMLString: true,
        customClass: 'student-detail-dialog'
      }
  );
};


const openit = async (rowData) => {
  try {

    await ElMessageBox.confirm(
        '确认将该学生转为教练身份吗？转换后将从学员列表移除',
        '身份转换',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const response = await change({
      studentId: rowData.id,
    });
    if (response.status === 1 && response.content === 'success')
    {
      ElMessage.success('身份转换成功，学员已移除');
      studentList.value = studentList.value.filter(student => student.id !== rowData.id);
      total.value--;
    }
    else
    {
      ElMessage.error('转换失败：' + (response.message || '服务器异常'));
    }
  }
  catch (error)
  {
    if (error.name === 'CanceledError')
    {
      ElMessage.info('已取消转换');
    }
    else
    {
      ElMessage.error('操作失败：' + (error.message || '服务器异常'));
    }
  }
};



const searchForm = ref({
  keyword: '',
  page: 1,
  size: 10,
  sortBy: 'create_time', // 默认按创建时间排序
  sortOrder: 'desc',    // 默认降序
  type: 'app'           // 只查询APP学员
});

// 生命周期钩子：页面加载时获取数据
onMounted(() => {
  fetchStudents();
});


const fetchStudents = async () => {
  loading.value = true;

  try {

    searchForm.value.page = currentPage.value;
    searchForm.value.size = pageSize.value;

    const response = await getStudents(
        {
          keyword: searchForm.value.keyword,
          page: searchForm.value.page,
          size: searchForm.value.size,
          sortBy: searchForm.value.sortBy,
          sortOrder: searchForm.value.sortOrder,
          type: searchForm.value.type,
        }
    );
    // console.log("完整响应数据：", response);
    // console.log("学员列表数据：", response.data.students); // 检查是否为数组
    // console.log("单条学员数据：", response.data.students[0]); // 检查字段是否匹配
    // console.log(response.content);
    if (response.status === 1 && response.content === "success")
      {
        studentList.value = response.data.students || [];
        total.value = response.data.total || 0;
        // console.log('Response:', response);
        // console.log('Students:', response.data.students);
      }
    else
        {
          ElMessage.error('获取学员列表失败');
        }
  }
  catch (error)
  {

    ElMessage.error('网络错误，请重试');
    router.push('/login');
  }
  finally
  {
    loading.value = false;
  }
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 切换页大小后重置为第一页
  fetchStudents();
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchStudents();
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  // 转换排序字段和顺序
  const sortMap = {
    'createTime': 'create_time',
    'name': 'name',
    'phone': 'phone'
  };

  const orderMap = {
    'ascending': 'asc',
    'descending': 'desc'
  };

  searchForm.value.sortBy = sortMap[prop] || 'create_time';
  searchForm.value.sortOrder = orderMap[order] || 'desc';

  fetchStudents();
};

// 获取VIP状态文本
const getVipStatusText = (status) => {
  const statusMap = {
    'activated': '已激活',
    'expired': '已过期',
    'none': '未开通'
  };
  return statusMap[status] || status;
};

</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body
{
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vh;
}

.all{
  width: 100%;
  height: 100%;
}
.all_content{
  display: flex;
  height: 100vh;
  width: 100%;
}
.side {
  height: 100%;
  width: 220px;
  background-color: #545c64;
  overflow: hidden;
}
.el-menu-vertical-demo
{
  width: 230px;

}
.all_main{
  width: 100vh;
  padding: 0px;
  margin: 0px;
}

.head {
  width: 100%;
  height: 4vh;
  display: flex;
  align-items: center;
  border-bottom: solid 1px rgba(204, 204, 204, 0.66);
}

.main{
  width: 100%;
 }

.item {
  padding-left: 30px;
}

.t {
  color: #090909;
  font-size: 18px;
  font-weight: 500;
}
.s{
  display: flex;
}
.search-area {
  justify-content: center;
  gap: 10px;
  align-items: center;
  width: 1000px;
  margin: 20px auto;
}

.table-wrapper {
  display: flex;
  justify-content: center;
  overflow-x: auto;
}
.pagination {
  display: flex;
  justify-content: center;
  font-family:"Times New Roman" ;
}


</style>